package middleware

import (
	"blog-server/global"
	"blog-server/utils"
	"bytes"
	"github.com/gin-gonic/gin"
	"time"
)

// CustomResponseWriter 封装 gin ResponseWriter 用于获取回包内容。
type CustomResponseWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w CustomResponseWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
} // 日志中间件。
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		ResponseWriter := &CustomResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		c.Writer = ResponseWriter
		// 打印请求信息
		reqBody, err := utils.ReadAll(c.Request.Body, 255)
		if err != nil {
			global.App.Log.Info("读取请求参数失败")
		}
		clientId := c.ClientIP()
		path := c.FullPath()
		method := c.Request.Method
		reqParams := string(reqBody)
		c.Request.Body = utils.NopCloser(bytes.NewBuffer(reqBody))
		c.Next()
		// 记录回包内容和处理时间
		end := time.Now()
		latency := end.Sub(start).String()
		respBody := string(ResponseWriter.body.Bytes())
		headerLog := "请求id" + clientId + "请求方法" + method + "请求路径" + path
		global.App.Log.Info(headerLog)
		global.App.Log.Info("请求信息" + reqParams)
		global.App.Log.Info("耗时" + latency + "响应体" + respBody)
	}
}
